package com.th.cash.th2.main

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.th.basemodel.base.BaseViewModel
import com.th.cash.th2.product.OrderUrlRequest
import com.th.cash.th2.product.ProductDetailRequest
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.debounce

class MainVm : BaseViewModel() {

    private val repository by lazy {
        MainRepository()
    }

    val intentChannel = Channel<MainIntent>(Channel.UNLIMITED)

    //可变状态数据流（读写）（StateFlow替代LiveData，难道每一个页面都需要定义一个）
    private val _uiState = MutableStateFlow<MainState>(MainState.Idle)

    //可观察状态数据流（只读）
    val uiState: StateFlow<MainState> get() = _uiState

    init {
        viewModelScope.launch {
            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is MainIntent.GetHome -> {
                        getHome()
                    }

                    is MainIntent.GetUserCenter -> {
                        getUserCenter()
                    }

                    is MainIntent.GetOrders -> {
                        getOrders(value.request)
                    }

                    is MainIntent.ApplyProduct -> {
                        applyProduct(value.request)
                    }

                    else -> {

                    }
                }
            }
        }
    }

    private fun getHome() {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getHome()

            result.checkResult(success = {
                loadSuccess()
                // 处理获取首页数据成功后的逻辑
                _uiState.value = MainState.HomeData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun getUserCenter() {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getUserCenter()

            result.checkResult(success = {
                loadSuccess()
                // 处理获取个人中心数据成功后的逻辑
                _uiState.value = MainState.UserCenterData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun getOrders(request: OrderRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getOrders(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理获取订单数据成功后的逻辑
                _uiState.value = MainState.OrderData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun applyProduct(request: ProductApplyRequest) {
        viewModelScope.launch {
            _uiState.value = MainState.Idle

            loadStartLoading()

            val result = repository.applyProduct(request)

            result.checkResult(success = { response ->
                loadSuccess()

                if (TextUtils.isEmpty(response?.ODKSaOjEmbowHJdsBQj)) {
                    return@checkResult
                }

                if (response!!.ODKSaOjEmbowHJdsBQj.startsWith("openapp://blwfqmqjJump/fivnqmqd5") && response.PfAByESPippinFrCMobf == 0
                ) {
                    getProductDetail(response.ODKSaOjEmbowHJdsBQj,ProductDetailRequest(request.KiOAYsXOverrelianceWWpzcfA))
                }else{
                    _uiState.value = MainState.ProductApply(response.ODKSaOjEmbowHJdsBQj+"&detail=info")
                }
            }, error = {
                loadError(it)
            })
        }
    }

    private fun getProductDetail(path: String, request: ProductDetailRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getProductDetail(request)

            result.checkResult(success = { response ->
                loadSuccess()

                if (TextUtils.isEmpty(response?.EuPVlTORenvoiZHVUeJY?.noneconomicSingle)) {
                    getOrderUrl(OrderUrlRequest(response?.QtlLPQXSonataCCkojtD?.pcVvsZyTotipalmationJWiscBh?:"","houijhyus"))
                }else{
                    _uiState.value = MainState.ProductApply("$path&detail=${response?.EuPVlTORenvoiZHVUeJY?.noneconomicSingle}&oid=${response?.QtlLPQXSonataCCkojtD?.pcVvsZyTotipalmationJWiscBh}")
                }
            }, error = {
                loadError(it)
            })
        }
    }

    private fun getOrderUrl(request: OrderUrlRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getOrderUrl(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理获取订单数据成功后的逻辑
                _uiState.value = MainState.ProductApply(it?.ODKSaOjEmbowHJdsBQj?:"")
            }, error = {
                loadError(it)
            })
        }
    }

}